package com.bungarus;

import com.bungarus.busi.TransferRemedy;
import com.bungarus.busi.TransferServerChildHandlerInitializer;
import com.bungarus.cluster.ClusterManager;
import com.bungarus.config.BungarusSpringConfig;
import com.bungarus.model.AbstractBungarusServerWithMultipleClients;
import io.netty.channel.ChannelHandler;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * Created by tang on 2018/11/24.
 */
public class Transfer extends AbstractBungarusServerWithMultipleClients {
    Logger logger = Logger.getLogger(Transfer.class);

    private static final int PORT_7600 = 7600;

    public static final String TAG = "transfer";
    /**
     * tag used to name the connecting cluster
     */
    public static final String CLUSTER_TAG_BUSI = "busi";
    /**
     * tags used to name the connecting clusters
     */
    private static final String[] CLUSTER_TAGS = {CLUSTER_TAG_BUSI};

    private static final ApplicationContext springContext =
            new AnnotationConfigApplicationContext(BungarusSpringConfig.class);

    private final ClusterManager clusterManager = new ClusterManager(TAG);

    public static void main(String[] args) throws Exception {
        int[] messagePorts = {PORT_7600};

        Transfer transfer = new Transfer();
        transfer.bind(messagePorts, null);
        transfer.initClusterAndConnectRemoteNode();
        transfer.initRemedy();
        transfer.listen(null);
    }

    @Override
    public void initRemedy() throws Exception {
        TransferRemedy.start(this);
    }

    @Override
    public ClusterManager getClusterManager() {
        return clusterManager;
    }

    @Override
    public ChannelHandler getChildHandlerInitializer() {
        return new TransferServerChildHandlerInitializer(this);
    }

    @Override
    protected MongoTemplate getMongoTemplate4FailedRetry() {
        return (MongoTemplate) Transfer.springContext.getBean("mongoTemplate");
    }

    @Override
    public String getTag() {
        return TAG;
    }

    @Override
    public String tagPortString4Connection() {
        return "(access|7600)";
    }

    @Override
    public String[] getRemoteNodeTags() {
        return CLUSTER_TAGS;
    }
}
